pub mod auth_controller;
pub mod role_controller;
pub mod transaction_controller;

use salvo::prelude::*;
use std::sync::Arc;
use tracing::{error, instrument};
use async_trait::async_trait;
use utils::response::{AppError, AppResult};

use crate::rpc::client::SystemRpcClient;
use utils::rpc::{RpcClientManager, RpcError};

/// 通用控制器 trait
#[async_trait]
pub trait Controller: Send + Sync + Clone {
    type RpcClient;

    /// 获取RPC客户端
    async fn get_rpc_client(&self) -> AppResult<Self::RpcClient>;
}

/// 基础控制器结构
#[derive(Clone)]
pub struct BaseController {
    rpc_manager: RpcClientManager,
}

impl BaseController {
    pub fn new(rpc_manager: RpcClientManager) -> Self {
        Self { rpc_manager }
    }

    pub fn rpc_manager(&self) -> &RpcClientManager {
        &self.rpc_manager
    }
}

/// 角色控制器
#[derive(Clone)]
pub struct RoleController {
    base: BaseController,
}

impl RoleController {
    pub fn new(rpc_manager: RpcClientManager) -> Self {
        Self {
            base: BaseController::new(rpc_manager),
        }
    }
}

#[async_trait::async_trait]
impl Controller for RoleController {
    type RpcClient = SystemRpcClient;

    #[instrument(skip(self))]
    async fn get_rpc_client(&self) -> AppResult<Self::RpcClient> {
        // 使用管理器创建RPC客户端
        Ok(SystemRpcClient::new(self.base.rpc_manager.clone()))
    }
}

/// 新的错误转换函数 - 推荐使用
/// 从 RpcError 转换为 AppError
pub fn convert_rpc_error_to_app_error(e: RpcError) -> AppError {
    error!("RPC调用失败: {:?}", e);
    match e {
        RpcError::NotFound(msg) => AppError::not_found(&msg),
        RpcError::InvalidArgument(msg) => AppError::validation(&msg),
        RpcError::ServiceDisabled(service) => {
            AppError::external_service(&format!("服务 {} 不可用", service))
        }
        RpcError::ConnectionFailed(err) => {
            AppError::rpc(&format!("RPC连接失败: {}", err))
        }
        RpcError::Unavailable(msg) => AppError::external_service(&msg),
        _ => AppError::internal("RPC服务器内部错误"),
    }
}

/// 新的错误转换函数 - 推荐使用
/// 从 tonic::Status 转换为 AppError
pub fn convert_tonic_status_to_app_error(status: tonic::Status) -> AppError {
    AppError::from_tonic_status(status)
}

/// 兼容性函数 - 保留原有API，用于向后兼容
/// 从 RpcError 转换为 StatusError（不推荐使用，建议迁移到 AppError）
pub fn convert_rpc_error(e: RpcError) -> StatusError {
    error!("RPC调用失败: {:?}", e);
    match e {
        RpcError::NotFound(msg) => StatusError::not_found().brief(msg),
        RpcError::InvalidArgument(msg) => StatusError::bad_request().brief(msg),
        RpcError::ServiceDisabled(service) => {
            StatusError::service_unavailable().brief(format!("服务 {} 不可用", service))
        }
        RpcError::ConnectionFailed(err) => {
            StatusError::internal_server_error().brief(format!("连接失败: {}", err))
        }
        RpcError::Unavailable(msg) => StatusError::service_unavailable().brief(msg),
        _ => StatusError::internal_server_error().brief("服务器内部错误"),
    }
}

/// 兼容性函数 - 保留原有API，用于向后兼容
/// tonic::Status 到 StatusError 的转换函数（不推荐使用，建议迁移到 AppError）
pub fn convert_tonic_status(e: tonic::Status) -> StatusError {
    error!("gRPC调用失败: {:?}", e);
    match e.code() {
        tonic::Code::NotFound => StatusError::not_found().brief(e.message()),
        tonic::Code::InvalidArgument => StatusError::bad_request().brief(e.message()),
        tonic::Code::Unavailable => StatusError::service_unavailable().brief(e.message()),
        tonic::Code::Unauthenticated => StatusError::unauthorized().brief(e.message()),
        tonic::Code::PermissionDenied => StatusError::forbidden().brief(e.message()),
        _ => StatusError::internal_server_error().brief("服务器内部错误"),
    }
}

/// 创建角色控制器实例
pub fn create_role_controller(rpc_manager: RpcClientManager) -> RoleController {
    RoleController::new(rpc_manager)
}

/// RPC 客户端注入中间件
#[derive(Clone)]
pub struct RpcClientMiddleware {
    client: Arc<SystemRpcClient>,
}

impl RpcClientMiddleware {
    pub fn new(manager: RpcClientManager) -> Self {
        Self {
            client: Arc::new(SystemRpcClient::new(manager)),
        }
    }
}

#[async_trait]
impl Handler for RpcClientMiddleware {
    async fn handle(
        &self,
        req: &mut Request,
        _depot: &mut Depot,
        _res: &mut Response,
        ctrl: &mut FlowCtrl,
    ) {
        req.extensions_mut().insert(self.client.clone());
        ctrl.call_next(req, _depot, _res).await;
    }
}

// use salvo::prelude::*;
// use serde::{Deserialize, Serialize};
// use utils::response::{AppError, AppResult};

// /// 通用控制器 trait
// #[async_trait::async_trait]
// pub trait Controller<TReq, TRes>: Send + Sync {
//     async fn handle(&self, req: TReq) -> AppResult<TRes>;
// }

// /// 通用的请求参数提取 trait
// pub trait FromRequest: Sized {
//     async fn from_request(req: &mut Request) -> AppResult<Self>;
// }

// /// 通用的 Handler 生成器
// pub async fn generic_handler<C, TReq, TRes>(
//     controller: C,
//     req: &mut Request,
// ) -> AppResult<impl Writer>
// where
//     C: Controller<TReq, TRes>,
//     TReq: FromRequest,
//     TRes: Serialize,
// {
//     let request = TReq::from_request(req).await?;
//     let response = controller.handle(request).await?;
//     Ok(Json(response))
// }

// /// 查询参数提取宏
// macro_rules! impl_query_from_request {
//     ($type:ty) => {
//         #[async_trait::async_trait]
//         impl FromRequest for $type {
//             async fn from_request(req: &mut Request) -> AppResult<Self> {
//                 Self::extract_from_query(req)
//             }
//         }
//     };
// }

// /// 路径参数提取宏
// macro_rules! impl_param_from_request {
//     ($type:ty, $param:literal) => {
//         #[async_trait::async_trait]
//         impl FromRequest for $type {
//             async fn from_request(req: &mut Request) -> AppResult<Self> {
//                 let id = req.param::<u64>($param)
//                     .ok_or_else(|| AppError::validation("参数无效"))?;
//                 Ok(Self::new(id))
//             }
//         }
//     };
// }

// /// JSON body 提取宏
// macro_rules! impl_json_from_request {
//     ($type:ty) => {
//         #[async_trait::async_trait]
//         impl FromRequest for $type {
//             async fn from_request(req: &mut Request) -> AppResult<Self> {
//                 req.parse_json().await
//                     .map_err(|e| AppError::validation_with_source("请求数据格式错误", e))
//             }
//         }
//     };
// }

// /// JSON + 路径参数提取宏
// macro_rules! impl_json_param_from_request {
//     ($type:ty, $param:literal) => {
//         #[async_trait::async_trait]
//         impl FromRequest for $type {
//             async fn from_request(req: &mut Request) -> AppResult<Self> {
//                 let id = req.param::<u64>($param)
//                     .ok_or_else(|| AppError::validation("参数无效"))?;
//                 let mut request: Self = req.parse_json().await
//                     .map_err(|e| AppError::validation_with_source("请求数据格式错误", e))?;
//                 request.set_id(id);
//                 Ok(request)
//             }
//         }
//     };
// }

// /// 简化 Handler 定义的宏
// macro_rules! handler {
//     ($name:ident, $controller:expr, $req_type:ty, $res_type:ty) => {
//         #[salvo::handler]
//         pub async fn $name(req: &mut Request) -> AppResult<impl Writer> {
//             generic_handler($controller, req).await
//         }
//     };
// }
